"use strict";
const express = require('express');
const router = express();
const fs = require("fs");

//获取终端配置搜索根目录
const [root = process.exit()] = [process.argv[2]];
const rootPath = root.endsWith('/') ? root : root + '/';
console.log(rootPath)
router.post('/search', (req, res) => {
    if(req.body.name.replace(/^\s*|\s*$/g, "") == '')return res.json('参数错误');
    console.log(getClientIp(req),req.body.name);
    const $ = req.body.name;
    const reg =
        $.startsWith("I")
            ? RegExp($.slice(1), "u")
            : RegExp($, "iu");
    const searchResults = {
        searchResultsList: [],
        length:'',
        totalTime: '',
    }

    const visit = path => {
        const list = [];
        for (let name of fs.readdirSync(path)) {
            try {
                const pathname = path + name;
                if (fs.statSync(pathname).isDirectory()) {
                    if (reg.test(name)) {
                        log(pathname + "/");
                        list.push(...visit(pathname + "/"));
                    } else {
                        list.push(pathname + "/");
                    }
                } else if (reg.test(name)) log(pathname);
            } catch (error) { }
        }
        return list.length === 1 ? visit(list[0]) : list;
    };

    const search = function* (path) {
        try {
            const head = {};
            let p = head;
            for (let i of visit(path)) {
                p = p.next = { value: search(i) };
            };
            while (head.next) {
                p = head;
                while (p.next) {
                    yield;
                    if (p.next.value.next().done) {
                        p.next = p.next.next;
                    } else {
                        p = p.next;
                    }
                }
            }
            yield;
        } catch (error) { console.log(error) }
    };

    let t2;
    const log = msg => {
        if (t2) {
            t2 = Date.now();
        } else {
            t2 = Date.now();
            // console.log("找出第一条结果的用时：" + (t2 - t1) + "ms");
        }
        // 去除文件之前的路径
        msg = msg.replace(rootPath, '/')
        searchResults.searchResultsList.push({ url: msg })
    };

    const t1 = Date.now();
    for (let i of search(rootPath + req.body.root));

    if (t2) {
        t2 = Date.now();
        // console.log("从开始搜索到找出最后一条结果的用时：" + (t2 - t1) + "ms");
        searchResults.length =  searchResults.searchResultsList.length;
        searchResults.totalTime =  time(t2, t1);
        res.json(searchResults);
    } else {
        t2 = Date.now();
        searchResults.totalTime =  time(t2, t1);
        res.json(searchResults);

    }

})
function getClientIp(req) {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
};
function time(t2, t1) {
    let diff = (t2 - t1) / 1000;
    return "耗时：" + diff % 60 + 's'
}

module.exports = () => {
    return router
}